package com.dd.cloud.user.service.phar.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.auth.req.role.UserBindRoleReq;
import com.dd.cloud.common.constants.MechanConstants;
import com.dd.cloud.common.constants.PharConstants;
import com.dd.cloud.user.entity.mechan.MechanBindPhar;
import com.dd.cloud.user.entity.phar.Pharmacy;
import com.dd.cloud.user.entity.phar.PharmacyRelatedProvince;
import com.dd.cloud.user.entity.phar.PharmacyUser;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.user.feign.AuthFeignService;
import com.dd.cloud.user.mapper.phar.PharmacyMapper;
import com.dd.cloud.user.req.phar.*;
import com.dd.cloud.user.res.phar.*;
import com.dd.cloud.user.service.mechan.IMechanBindPharService;
import com.dd.cloud.user.service.mechan.IMechanRankService;
import com.dd.cloud.user.service.phar.IPharmacyRelatedProvinceService;
import com.dd.cloud.user.service.phar.IPharmacyService;
import com.dd.cloud.user.service.phar.IPharmacyUserService;
import com.dd.cloud.user.service.product.IPayParamService;
import com.dd.cloud.user.service.role.IAdminPowerService;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 药房表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-09-23
 */
@Slf4j
@Service
public class PharmacyServiceImpl extends ServiceImpl<PharmacyMapper, Pharmacy> implements IPharmacyService {
    @Autowired
    IPharmacyRelatedProvinceService pharmacyRelatedProvinceService;
    @Autowired
    private IMechanRankService mechanRankService;
    @Autowired
    private IMechanBindPharService mechanBindPharService;
    @Autowired
    private IPharmacyUserService pharmacyUserService;
    @Autowired
    private IAdminPowerService adminPowerService;
    @Autowired
    private IPayParamService payParamService;
    @Autowired
    private AuthFeignService authFeignService;


    /**
     * 获取机构使用的药房
     *
     * @param mechanId 机构id, 不传查询登录人的机构id
     * @return
     */
    @Override
    public Pharmacy getPharmacy(Integer mechanId) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        if (mechanId == null) {
            mechanId = loginInfo.getMechanId();
        }
        PharmacyRelatedProvince res = pharmacyRelatedProvinceService.getPharRelatedMechan(mechanId);
        if (res == null) {
            throw new ZekeException(400, "未找到默认使用的药房, 请联系管理员");
        }
        Pharmacy pharmacy = getById(res.getPharId());
        if (pharmacy == null) {
            throw new ZekeException(400, "药房id" + res.getPharId() + "不存在");
        }
        return pharmacy;
    }

    /**
     * 获取药房标识
     *
     * @param id
     * @return
     */
    @Override
    public Integer getPharmacyFlag(Integer id) {
        QueryWrapper<Pharmacy> qw = new QueryWrapper<>();
        qw.lambda().eq(Pharmacy::getId, id);
        qw.lambda().select(Pharmacy::getFlag);
        Pharmacy pharmacy = getOne(qw);
        if (pharmacy != null) {
            return pharmacy.getFlag();
        }
        return -1;
    }

    /**
     * 统计药房首页头部数据
     *
     * @return
     */
    @Override
    public PharmacyHomeTopStatisticsRes statisticsPharmacyHomeTop() {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.PHAR).get();
        Integer pharmacyId = loginInfo.getPharId();
        return getBaseMapper().statisticsPharmacyHomeTop(pharmacyId);
    }

    /**
     * 统计药房首页近期收入情况数据
     *
     * @param req
     * @return
     */
    @Override
    public PharmacyHomeChartStatisticsRes statisticsPharmacyHomeChart(PharmacyHomeChartStatisticsReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.PHAR).get();
        req.setPharmacyId(loginInfo.getPharId());
        if (req.verify()) {
            throw new ZekeException(400, "日期参数错误");
        }
        int type = 1;
        if (req.getStart() == null && req.getEnd() == null) {
            req.setEnd(LocalDateTime.now());
            switch (req.getFlag()) {
                case 1:
                    req.setStart(req.getEnd().withHour(0).withMinute(0).withSecond(0));
                    req.setSqlSegment("custom_hour(pp.create_date)");
                    break;
                case 2:
                    req.setStart(DateUtils.getFirstDayOfWeek(req.getEnd().toLocalDate()));
                    req.setSqlSegment("date_format(pp.create_date, '%c-%e')");
                    type = 2;
                    break;
                case 3:
                    req.setStart(DateUtils.getFirstDayOfMonth(req.getEnd().toLocalDate()));
                    req.setSqlSegment("date_format(pp.create_date, '%c-%e')");
                    type = 2;
                    break;
                case 4:
                    QueryWrapper<Pharmacy> qw = new QueryWrapper<>();
                    qw.lambda().eq(Pharmacy::getId, req.getPharmacyId());
                    qw.lambda().select(Pharmacy::getCreateDate);
                    Pharmacy pharmacy = getOne(qw);
                    req.setStart(pharmacy.getCreateDate());
                    req.setSqlSegment("date_format(pp.create_date, '%Y-%c')");
                    type = 3;
                    break;
                default:
                    throw new ZekeException(400, "未知标识参数");
            }
        } else {
            type = 4;
            req.setSqlSegment("date_format(pp.create_date, '%Y-%c-%e')");
        }
        List<PharmacyHomeChartStatisticsListRes> valueList = getBaseMapper().statisticsListPharmacyHomeChartList(req);
        LocalDateTime start = req.getStart();
        LocalDateTime end = req.getEnd();
        LocalDateTime lastStart = null;
        LocalDateTime lastEnd = null;
        Map<String, PharmacyHomeChartStatisticsListRes> map = valueList.stream().collect(Collectors.toMap(PharmacyHomeChartStatisticsListRes::getKey, t -> t));
        List<PharmacyHomeChartStatisticsListRes> tempList = new ArrayList<>();
        PharmacyHomeChartStatisticsRes res = new PharmacyHomeChartStatisticsRes();
        if (type == 1) {
            for (String time : PharmacyHomeChartStatisticsRes.TIME_ARR) {
                PharmacyHomeChartStatisticsListRes temp = new PharmacyHomeChartStatisticsListRes();
                PharmacyHomeChartStatisticsListRes item = map.get(time);
                if (item == null) {
                    temp.setKey(time);
                    temp.setValue("0");
                    tempList.add(temp);
                } else {
                    tempList.add(item);
                }
            }
            lastStart = req.getStart().minusDays(1);
            lastEnd = lastStart.toLocalDate().atTime(LocalTime.MAX);
        } else if (type == 2) {
            int max = req.getFlag() == 1 ? 7 : 31;
            for (int i = 0; i < max; i++) {
                PharmacyHomeChartStatisticsListRes temp = new PharmacyHomeChartStatisticsListRes();
                if (start.compareTo(LocalDateTime.now()) > 0) {
                    break;
                }
                int month = start.getMonthValue();
                int day = start.getDayOfMonth();
                PharmacyHomeChartStatisticsListRes item = map.get(month + "-" + day);
                if (item == null) {
                    temp.setKey(month + "-" + day);
                    temp.setValue("0");
                    tempList.add(temp);
                } else {
                    tempList.add(item);
                }
                start = start.plusDays(1);
            }
            lastStart = req.getStart().minusWeeks(1);
            lastEnd = DateUtils.getLastDayOfWeek(lastStart.toLocalDate());
            if (req.getFlag() == 3) {
                lastStart = req.getStart().minusMonths(1);
                lastEnd = DateUtils.getLastDayOfMonth(lastStart.toLocalDate());
            }
        } else if (type == 3) {
            int currYear = LocalDate.now().getYear();
            while (start.compareTo(end) <= 0) {
                PharmacyHomeChartStatisticsListRes temp = new PharmacyHomeChartStatisticsListRes();
                int year = start.getYear();
                int month = start.getMonthValue();
                PharmacyHomeChartStatisticsListRes item = map.get(year + "-" + month);
                if (item == null) {
                    if (currYear != year) {
                        temp.setKey(year + "年" + month + "月");
                    } else {
                        temp.setKey(month + "月");
                    }
                    temp.setValue("0");
                    tempList.add(temp);
                } else {
                    if (currYear != year) {
                        item.setKey(year + "年" + month + "月");
                    } else {
                        item.setKey(month + "月");
                    }
                    tempList.add(item);
                }
                start = start.plusMonths(1);
            }
        } else {
            int currYear = LocalDate.now().getYear();
            while (start.compareTo(end) <= 0) {
                PharmacyHomeChartStatisticsListRes temp = new PharmacyHomeChartStatisticsListRes();
                int year = start.getYear();
                int month = start.getMonthValue();
                int day = start.getDayOfMonth();
                PharmacyHomeChartStatisticsListRes item = map.get(year + "-" + month + "-" + day);
                if (item == null) {
                    if (currYear != year) {
                        temp.setKey(year + "年" + month + "月" + day + "日");
                    } else {
                        temp.setKey(month + "月" + day + "日");
                    }
                    temp.setValue("0");
                    tempList.add(temp);
                } else {
                    if (currYear != year) {
                        item.setKey(year + "年" + month + "月" + day + "日");
                    } else {
                        item.setKey(month + "月" + day + "日");
                    }
                    tempList.add(item);
                }
                start = start.plusDays(1);
            }
        }
        res.setValueList(tempList);
        Integer thisIncome = getBaseMapper().statisticsListPharmacyHomeCharTotalIncome(req);
        res.setThisIncome(thisIncome == null ? 0 : thisIncome);
        if (lastStart != null && lastEnd != null) {
            req.setStart(lastStart);
            req.setEnd(lastEnd);
            Integer lastIncome = getBaseMapper().statisticsListPharmacyHomeCharTotalIncome(req);
            res.setLastIncome(lastIncome == null ? 0 : lastIncome);
            if (res.getThisIncome() == 0 && res.getLastIncome() == 0) {
                res.setGrowthRate(0);
            } else if (res.getThisIncome() > 0 && res.getLastIncome() == 0) {
                res.setGrowthRate(100);
            } else {
                res.setGrowthRate((int) (BigDecimalUtils.divide(res.getThisIncome(), res.getLastIncome()).doubleValue() * 100));
            }
        }
        return res;
    }

    /**
     * 统计药房首页药品总用量排行榜
     *
     * @param req
     * @return
     */
    @Override
    public IPage<PharmacyHomeDrugDosageStatisticsRes> statisticsPharmacyHomeDrugDosage(PharmacyHomeDrugDosageStatisticsReq req) {
        req.setPageSize(20);
        if (req.getPage() > 5) {
            throw new ZekeException(400, "最大前100条药品数据");
        }
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.PHAR).get();
        req.setPharmacyId(loginInfo.getPharId());
        IPage<PharmacyHomeDrugDosageStatisticsRes> iPage = req.pagePojo();
        List<PharmacyHomeDrugDosageStatisticsRes> list = getBaseMapper().statisticsPharmacyHomeDrugDosage(req.getPharmacyId());
        double total = list.stream().mapToDouble(t -> t.getDosage().doubleValue()).sum();
        BigDecimal totalDosage = BigDecimal.valueOf(total);
        log.info("total:{},totalDosage:{}", total, totalDosage);
        if (!totalDosage.equals(BigDecimal.ZERO)) {
            for (PharmacyHomeDrugDosageStatisticsRes item : list) {
                if (item.getDosage().equals(BigDecimal.ZERO)) {
                    item.setDosageScale(0);
                }
                item.setDosageScale(BigDecimalUtils.divide(item.getDosage(), totalDosage).multiply(BigDecimal.valueOf(100)).intValue());
            }
        }
        iPage.setTotal(list.size());
        int size = list.size() == 0 ? 0 : list.size() - 1;
        int offset = Math.toIntExact(iPage.offset());
        int endOffset = offset + 20;
        if (offset > size) {
            throw new ZekeException(400, "当前页没有数据");
        }
        if (endOffset > size) {
            endOffset = size + 1;
        }
        if (size == 0) {
            iPage.setRecords(list);
        } else {
            iPage.setRecords(list.subList(offset, endOffset));
        }
        return iPage;
    }

    /**
     * 查询药房可查询的机构 下拉框使用
     *
     * @return
     */
    @Override
    public List<PharmacyMechanSelectRes> queryPharmacyMechanSelect() {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.PHAR).get();
        return getBaseMapper().queryPharmacyMechanSelect(loginInfo.getPharId());
    }

    /**
     * 查询药房开始收入时间
     *
     * @return
     */
    @Override
    public LocalDateTime queryFirstPharmacyIncomeDate() {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.PHAR).get();
        LocalDateTime firstDate = getBaseMapper().queryFirstPharmacyIncomeDate(loginInfo.getPharId());
        return firstDate == null ? LocalDateTime.now() : firstDate;
    }

    /**
     * @param req:
     * @return void
     * @description 添加药房数据
     * @author czg
     * @date 2023/4/25 11:39
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPharmacy(AddPharmacyReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        if (req.getType() == PharConstants.Type.SELF && (req.getMechanIdList() == null || req.getMechanIdList().isEmpty())) {
            throw new ZekeException("私有药房请选择机构");
        }
        QueryWrapper<Pharmacy> qw = new QueryWrapper<>();
        qw.lambda().eq(Pharmacy::getName, req.getName())
                .ne(Pharmacy::getStatus, PharConstants.PharStatus.DEL);
        Pharmacy one = getOne(qw);
        if (one != null) {
            throw new ZekeException("药房名字已存在");
        }
        qw.clear();
        qw.lambda().eq(Pharmacy::getAdminPhone, req.getAdminPhone())
                .ne(Pharmacy::getStatus, PharConstants.PharStatus.DEL);
        one = getOne(qw);
        if (one != null) {
            throw new ZekeException("药房管理员手机号已存在");
        }
        QueryWrapper<PharmacyUser> qll = new QueryWrapper<>();
        qll.lambda().eq(PharmacyUser::getPhone, req.getAdminPhone())
                .ne(PharmacyUser::getStatus, PharConstants.StoreUserStatus.DEL);
        PharmacyUser user = pharmacyUserService.getOne(qll);
        if (user != null) {
            throw new ZekeException("药房管理员手机号已存在");
        }
        one = new Pharmacy();
        BeanUtils.copyProperties(req, one);
        one.setCreateDate(LocalDateTime.now());
        one.setFlag(PharConstants.Flag.STORE);
        one.setStatus(PharConstants.PharStatus.NOMER);
        int insert = getBaseMapper().insert(one);
        if (insert <= 0) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
        if (one.getFlag() == PharConstants.Flag.STORE) {
            List<Integer> integers = mechanRankService.queryNotExistsMechanId(new ArrayList<>(req.getMechanIdList()));
            if (integers != null && !integers.isEmpty()) {
                throw new ZekeException("机构id" + StringUtils.join(integers, ",") + "不存在");
            }
            Pharmacy finalOne = one;
            req.getMechanIdList().forEach(id -> {
                QueryWrapper<MechanBindPhar> qs = new QueryWrapper<>();
                qs.lambda().eq(MechanBindPhar::getMechanId, id)
                        .eq(MechanBindPhar::getPharId, finalOne.getId())
                        .eq(MechanBindPhar::getStatus, MechanConstants.BindPharStaus.NORMAL);
                MechanBindPhar bindPhar = mechanBindPharService.getOne(qs);
                if (bindPhar == null) {
                    bindPhar = new MechanBindPhar();
                    bindPhar.setMechanId(id);
                    bindPhar.setPharId(finalOne.getId());
                    bindPhar.setStatus(MechanConstants.BindPharStaus.NORMAL);
                    bindPhar.setCreateDate(LocalDateTime.now());
                    boolean save = mechanBindPharService.save(bindPhar);
                    if (!save) {
                        throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
                    }
                }
            });
        }
        /**
         * 新增管理员, 并设置权限
         */
        PharmacyUser pharmacyUser = new PharmacyUser();
        pharmacyUser.setCreateDate(LocalDateTime.now());
        pharmacyUser.setCreateId(loginInfo.getId());
        pharmacyUser.setEmail(req.getAdminEmail());
        pharmacyUser.setNickName(req.getAdminName());
        pharmacyUser.setPharId(one.getId());
        pharmacyUser.setPhone(req.getAdminPhone());
        pharmacyUser.setStatus(PharConstants.StoreUserStatus.NOMER);
        String salt = CodecUtils.generateSalt();
        pharmacyUser.setSalt(salt);
        pharmacyUser.setPassword(CodecUtils.md5Hex(pharmacyUser.getPhone().substring(pharmacyUser.getPhone().length() - 6), pharmacyUser.getSalt()));
        int save = pharmacyUserService.getBaseMapper().insert(pharmacyUser);
        if (save <= 0) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
        //添加药房管理员的超管权限
        UserBindRoleReq bindRoleReq = new UserBindRoleReq();
        bindRoleReq.setUserId(pharmacyUser.getId());
        bindRoleReq.setType(LoginInfo.UserType.PHAR);
        bindRoleReq.setRoleName("超级管理员");
        ResponseEntity<Integer> response = authFeignService.userBindRole(bindRoleReq);
//        Integer roleId = adminPowerService.queryAdminRoleId(LoginInfo.UserType.PHAR);
//        if (roleId == null) {
//            throw new ZekeException(400, "超管权限查询失败");
//        }
//        adminPowerService.bindUserRole(pharmacyUser.getId(), roleId, LoginInfo.UserType.PHAR);
        payParamService.initPharmacyPayParam(one.getId());
    }

    /**
     * @param req:
     * @return void
     * @description 修改药房数据
     * @author czg
     * @date 2023/4/25 15:07
     */
    @Override
    public void updatePharmacy(UpdatePharmacyReq req) {
        if (req.getType() == PharConstants.Type.SELF && (req.getMechanIdList() == null || req.getMechanIdList().isEmpty())) {
            throw new ZekeException("私有药房请选择机构");
        }
        Pharmacy pharmacy = getById(req.getId());
        if (pharmacy == null) {
            throw new ZekeException("药房不存在");
        }
        if (!req.getName().equals(pharmacy.getName())) {
            //修改了药房名
            QueryWrapper<Pharmacy> qw = new QueryWrapper<>();
            qw.lambda().eq(Pharmacy::getName, req.getName())
                    .ne(Pharmacy::getStatus, PharConstants.PharStatus.DEL);
            Pharmacy one = getOne(qw);
            if (one != null) {
                throw new ZekeException("药房名字已存在");
            }
        }
        if (!req.getAdminPhone().equals(pharmacy.getAdminPhone())) {
            //修改了管理员手机号
            QueryWrapper<Pharmacy> qw = new QueryWrapper<>();
            qw.lambda().eq(Pharmacy::getAdminPhone, req.getAdminPhone())
                    .ne(Pharmacy::getStatus, PharConstants.PharStatus.DEL);
            Pharmacy phOne = getOne(qw);
            if (phOne != null) {
                throw new ZekeException("药房管理员手机号已存在");
            }
            QueryWrapper<PharmacyUser> qll = new QueryWrapper<>();
            qll.lambda().eq(PharmacyUser::getPhone, req.getAdminPhone())
                    .ne(PharmacyUser::getStatus, PharConstants.StoreUserStatus.DEL);
            PharmacyUser user = pharmacyUserService.getOne(qll);
            if (user != null) {
                throw new ZekeException("药房管理员手机号已存在");
            }
            UpdateWrapper<PharmacyUser> uw = new UpdateWrapper<>();
            uw.lambda().eq(PharmacyUser::getPhone, pharmacy.getAdminPhone())
                    .ne(PharmacyUser::getStatus, PharConstants.StoreUserStatus.DEL)
                    .eq(PharmacyUser::getPharId, req.getId())
                    .set(PharmacyUser::getPhone, req.getAdminPhone());
            boolean update = pharmacyUserService.update(uw);
            if (!update) {
                throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
            }
        }
        //如果是从私有药房转到公共药房, 删除所有机构绑定关系
        if (req.getType() == PharConstants.Type.PUBLIC && pharmacy.getType() == PharConstants.Type.SELF) {
            UpdateWrapper<MechanBindPhar> ws = new UpdateWrapper<>();
            ws.lambda().eq(MechanBindPhar::getPharId, pharmacy.getId())
                    .ne(MechanBindPhar::getStatus, PharConstants.PharStatus.DEL)
                    .set(MechanBindPhar::getStatus, PharConstants.PharStatus.DEL);
            mechanBindPharService.update(ws);
        }

        BeanUtils.copyProperties(req, pharmacy);
        pharmacy.setUpdateDate(LocalDateTime.now());
        if (req.getType() == PharConstants.Type.SELF) {
            pharmacy.setFlag(PharConstants.Flag.STORE);
        } else {
            pharmacy.setFlag(PharConstants.Flag.NOT);
        }
        int update = getBaseMapper().updateById(pharmacy);
        if (update <= 0) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
        if (pharmacy.getFlag() == PharConstants.Flag.STORE) {
            QueryWrapper<MechanBindPhar> ql = new QueryWrapper<>();
            ql.lambda().eq(MechanBindPhar::getPharId, req.getId())
                    .eq(MechanBindPhar::getStatus, MechanConstants.BindPharStaus.NORMAL);
            List<MechanBindPhar> list = mechanBindPharService.list(ql);
            List<Integer> exIds = list.stream().map(MechanBindPhar::getMechanId).collect(Collectors.toList());
            //要去掉的数据
            List<Integer> idsPlus = NumberUtils.nexistent(exIds, req.getMechanIdList());
            //要新增的数据
            List<Integer> idsAdd = NumberUtils.nexistent(req.getMechanIdList(), exIds);
            if (!idsPlus.isEmpty()) {
                //修改要去掉的数据
                UpdateWrapper<MechanBindPhar> uw = new UpdateWrapper<>();
                uw.lambda().in(MechanBindPhar::getMechanId, idsPlus)
                        .set(MechanBindPhar::getStatus, MechanConstants.BindPharStaus.DEL)
                        .eq(MechanBindPhar::getPharId, req.getId());
                mechanBindPharService.update(uw);
            }
            if (!idsAdd.isEmpty()) {
                List<MechanBindPhar> addList = new ArrayList<>();
                idsAdd.forEach(ids -> {
                    //新增要加入的数据
                    MechanBindPhar bindPhar = new MechanBindPhar();
                    bindPhar.setMechanId(ids);
                    bindPhar.setPharId(req.getId());
                    bindPhar.setStatus(MechanConstants.BindPharStaus.NORMAL);
                    bindPhar.setCreateDate(LocalDateTime.now());
                    addList.add(bindPhar);
                });
                mechanBindPharService.saveBatch(addList);
            }
        }
    }

    /**
     * @param id:     id
     * @param status: 状态
     * @return void
     * @description 修改药房状态
     * @author czg
     * @date 2023/4/25 17:51
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePharmacyStatus(Integer id, Integer status) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        Pharmacy pharmacy = getById(id);
        if (pharmacy == null) {
            throw new ZekeException("药房不存在");
        }
        if (pharmacy.getStatus().equals(status)) {
            return;
        }
        if (!ObjectUtils.refrect(PharConstants.PharStatus.class, status)) {
            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
        }
        pharmacy.setStatus(status);
        if (status == PharConstants.PharStatus.SIGNOUT) {
            pharmacy.setLogoutDate(LocalDateTime.now());
            pharmacy.setLogoutName(loginInfo.getName());
        }
        boolean i = updateById(pharmacy);
        if (!i) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
        if (status == PharConstants.PharStatus.DEL || status == PharConstants.PharStatus.SIGNOUT) {
            UpdateWrapper<PharmacyUser> uw = new UpdateWrapper<>();
            uw.lambda().set(PharmacyUser::getStatus, status)
                    .eq(PharmacyUser::getPharId, id);
            pharmacyUserService.update(uw);
        }

    }

    /**
     * @param req:
     * @return Page<PharmacyPageRes>
     * @description 分页查询药房数据
     * @author czg
     * @date 2023/4/25 16:19
     */
    @Override
    public Page<PharmacyPageRes> getPharmacyPage(PharmacyPageReq req) {
        Page<PharmacyPageRes> page = req.pagePojo();
        if (StringUtils.isBlank(req.getStatus())) {
            req.setStatus(PharConstants.PharStatus.STATUS);
        }
        if (!StringUtils.isBlank(req.getStatus())) {
            req.setStatusStr(req.getStatus().split(","));
        }
        return getBaseMapper().getPharmacyPage(page, req);
    }

    /**
     * @param ids: 药房ids 数组
     * @return List<PharListRes>  药房列表
     * @description 查询药房list
     * @author czg
     * @date 2023/6/16 10:11
     */
    @Override
    public List<PharListRes> getPharmacyList(Integer[] ids) {
        QueryWrapper<Pharmacy> qw = new QueryWrapper<>();
        qw.lambda().eq(Pharmacy::getStatus, PharConstants.PharStatus.NOMER)
                .select(Pharmacy::getId, Pharmacy::getName);
        if (ids != null && ids.length > 0) {
            qw.lambda().in(Pharmacy::getId, ids);
        }
        List<Pharmacy> list = list(qw);
        List<PharListRes> collect = list.stream().map(item -> {
            PharListRes res = new PharListRes();
            res.setPharId(item.getId());
            res.setPharName(item.getName());
            return res;
        }).collect(Collectors.toList());
        return collect;
    }
}
